<template>
  <view>
    <camera
      v-if="!tempImagePath && cameraHeight !== 0"
      :resolution="'high'"
      :frame-size="'large'"
      :device-position="device"
      :flash="flash"
      :style="{
        position: 'fixed',
        top: '0',
        width: cameraWidth + 'px',
        height: cameraHeight + 'px',
      }"
    ></camera>
    <image v-else :src="tempImagePath" mode="widthFix" style="width: 100%; position: absolute" />
    <!-- 预览 -->
    <canvas
      type="2d"
      id="canvasView"
      :style="{
        width: cameraWidth + 'px',
        height: cameraHeight + 'px',
      }"
    ></canvas>
    <view class="handle" id="myContainer">
      <button class="handle_card" @click="chooseLocaClick">
          <!-- <image
            class="handle_card_icon"
            :src="`${imgUrl}/watermark/watermark-loca.png`"
            mode="widthFix"
          /> -->
          <view class="handle_card_name">定位</view>
        </button>
        <button class="handle_card" @click="setDevice">
          <!-- <image
            class="handle_card_icon"
            :src="`${imgUrl}/watermark/watermark-turn.png`"
            mode="widthFix"
          /> -->
          <view class="handle_card_name">切换</view>
        </button>
      <button class="handle_ps" @click="takePhoto">
        <!-- <image class="handle_ps_image" :src="`${imgUrl}/watermark/watermark-shoot.png`" mode="widthFix" /> -->
        <view class="handle_ps_name">拍摄</view>
      </button>
      <button class="handle_card" @click="setFlash">
          <!-- <image
            class="handle_card_icon"
            :src="`${imgUrl}/watermark/watermark-flash.png`"
            mode="widthFix"
          /> -->
          <view class="handle_card_name">闪光</view>
        </button>
        <button class="handle_card" open-type="share">
          <!-- <image
            class="handle_card_icon"
            :src="`${imgUrl}/watermark/watermark-share.png`"
            mode="widthFix"
          /> -->
          <view class="handle_card_name">分享</view>
        </button>
    </view>
  </view>
</template>
<script>
// const mapSDK = new QQMapWX({
//   key: 'UWHBZ-3AEKX-5U74E-7SFQY-BRJO3-O2BUV', //申请的开发者秘钥key
// })
import { rotateAndCropImage } from '@/utils/camera'
import { deleteWxFile } from '@/utils/file'
import { showToast, showLoading,hideLoading,hideToast } from '@/utils/toast'
// import { showToast, showLoading } from "@/js/common.js";
export default {
  data() {
    return {
      device: 'back',
      flash: '',
      date: '',
      time: '',
      week: '',
      address: '',
      addressName: '',
      cameraWidth: 0,
      cameraHeight: 0,
      canvasWidth: 0,
      canvasHeight: 0,
      tempImagePath: '',
      timer: null,
      // 文本是否换行
      isWrap: false,
    }
  },
  created() {
    const systemInfo = uni.getSystemInfoSync()
    const screenWidth = systemInfo.screenWidth
    const screenHeight = systemInfo.screenHeight
    const statusBarHeight = systemInfo.statusBarHeight
    const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
    const cameraWidth = screenWidth
    uni
      .createSelectorQuery()
      .select('#myContainer')
      .boundingClientRect(rect => {
        const cameraHeight = screenHeight - statusBarHeight - menuButtonInfo.height - (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 - rect.height
        this.cameraWidth = cameraWidth
        this.cameraHeight = cameraHeight
        this.getTime()
        this.getLocation()
      })
      .exec()
  },
  methods: {
    // 获取天气
    getAnonInfo() {
      //   anonWeatherInfoApi({
      //     city: this.ad_info.adcode,
      //   }).then((res) => {
      //     if (res.status === 200) {
      //       this.cityObj = res.data;
      //       // 获取完天气后初始化画图
      //       this.drawCanvas("#canvasView", "init");
      //     }
      //   });
      this.drawCanvas('#canvasView', 'init')
    },
    // 画图
    drawCanvas(canvasId, type) {
      console.log('---------type',type)
      const _this = this
      return new Promise(resolve => {
        if (type == 'init') {
          const query = uni.createSelectorQuery()
          console.log('---------query',query)
          query
            .select(canvasId)
            .fields({
              node: true,
            })
            .exec(res => {
              ctxFn(res[0].node)
            })
        } else {
          // 创建离屏 2D canvas 实例
         
          const node = uni.createOffscreenCanvas({
            type: '2d',
          })
          console.log('---------node',node)
          ctxFn(node)
        }
        function ctxFn(node) {
          console.log('---------ctxFn node',node)
          const canvas = node
          const ctx = canvas.getContext('2d')
          let camerW = null
          let camerH = null
          if (type === 'init') {
            camerW = _this.cameraWidth
            camerH = _this.cameraHeight
            const drp = uni.getWindowInfo().pixelRatio
            canvas.width = camerW * drp
            canvas.height = camerH * drp
            ctx.scale(drp, drp)
            draw()
          } else {
            camerW = _this.canvasWidth
            camerH = _this.canvasHeight
            canvas.width = camerW
            canvas.height = camerH
            const image = canvas.createImage()
            image.src = _this.tempImagePath
            image.onload = () => {
              ctx.drawImage(image, 0, 0)
              draw()
            }
          }
          function draw() {
            console.log('---------draw node')
            const sizeX = camerW / 375
            // 判断地址是否超出边界
            if (_this.isWrap) {
              camerH -= 15 * sizeX
            }
            ctx.font = `${35 * sizeX}px 黑体`
            ctx.fillStyle = '#ffffff'
            ctx.textBaseline = 'bottom'
            // 绘制时间
            ctx.fillText(_this.time, 10 * sizeX, camerH - 30 * sizeX)
            const timeWidth = ctx.measureText(_this.time).width
            // 绘制边框线条
            ctx.beginPath()
            ctx.lineCap = 'round'
            ctx.moveTo(timeWidth + 16 * sizeX, camerH - 59 * sizeX)
            ctx.lineTo(timeWidth + 16 * sizeX, camerH - 36 * sizeX)
            ctx.lineWidth = 1.7 * sizeX
            ctx.strokeStyle = '#A9A9A8'
            ctx.stroke()
            // 绘制年月日
            ctx.font = `${12 * sizeX}px 黑体`
            ctx.fillText(_this.date, timeWidth + 22 * sizeX, camerH - 49 * sizeX)
            // 绘制周几
            ctx.fillText(_this.week, timeWidth + 22 * sizeX, camerH - 34 * sizeX)
            // 绘制天气
            const city = `80°C`
            ctx.fillText(city, timeWidth + 60 * sizeX, camerH - 34 * sizeX)
            // 绘制换行地址
            ctx.font = `bold ${14 * sizeX}px 黑体`
            _this.drawText(ctx, _this.address, 10 * sizeX, camerH - 10 * sizeX, camerW)
            if (type !== 'init') {
              const imgData = canvas.toDataURL()
              console.log('---------filePath '+imgData)
              const time = new Date().getTime()
              const fs = uni.getFileSystemManager()
              const filePath = '/poster' + time + 'share' + '.png'
              console.log('---------filePath '+filePath)
              fs.writeFile({
                filePath,
                data: imgData.replace(/^data:image\/\w+;base64,/, ''),
                encoding: 'base64',
                success: () => {
                  console.log('---------filePath '+filePath)
                  resolve(filePath)
                },
              })
            }
          }
        }
      })
    },
    // 获取并更新时间的方法
    getTime() {
      this.timeSet()
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      this.timer = setInterval(() => {
        this.timeSet()
        // this.drawCanvas('#canvasView', 'init')
      }, 1000)
    },
    // 时间更新
    timeSet() {
      const timeData = this.formatTime()
      this.date = timeData.date
      this.time = timeData.time
      this.week = timeData.week
    },
    // 获取并更新位置信息的方法
    getLocation() {
      const that = this
      uni.getLocation({
        type: 'gcj02',

        geocode: true,
        isHighAccuracy: true,
        success: function (res) {
          // that.longitude = res.longitude
          // that.latitude = res.latitude
          // 标记
          // that.marker[0].latitude = res.latitude
          // that.marker[0].longitude = res.longitude
          console.log('当前位置的经度：' + res.longitude)
          console.log('当前位置的纬度：' + res.latitude)
          wx.request({
            url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=UWHBZ-3AEKX-5U74E-7SFQY-BRJO3-O2BUV`,
            success(res) {
              console.log(res, '定位')
              that.address = res.data.result.address
              //       // 获取天气
              // this.ad_info =  res.data.result.address
              that.getAnonInfo()
            },
          })
        },
      })
      // uni.getLocation({
      //   isHighAccuracy: true,
      //   type: 'gcj02',
      //   success: Locares => {
      //     locationToAddress(Locares).then(res => {
      //       this.address = `${res.address_component.city}${res.formatted_addresses.recommend}`
      //       // 获取天气
      //       this.ad_info = res.ad_info
      //       this.getAnonInfo()
      //     })
      //   },
      // })
    },
    // 绘制换行文本
    drawText(ctx, str, leftWidth, initHeight, canvasWidth) {
      let lineWidth = 0
      let lastSubStrIndex = 0
      this.isWrap = false
      for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width
        if (lineWidth > canvasWidth - 20) {
          this.isWrap = true
          ctx.fillText(str.slice(lastSubStrIndex, i), leftWidth, initHeight)
          initHeight += (15 * canvasWidth) / 375
          lineWidth = 0
          lastSubStrIndex = i
        }
      }
      ctx.fillText(str.slice(lastSubStrIndex), leftWidth, initHeight)
    },
    // 拍摄事件
    takePhoto() {
      const ctx = uni.createCameraContext()
      ctx.takePhoto({
        quality: 'normal',
        success: res => {
          showLoading('图片生成中...')
          // 兼容横屏旋转，如果宽度大于高度，旋转90度，否则不旋转
          const isEdg = res.width > res.height
          console.log('---------tempImagePath',res.tempImagePath)
          rotateAndCropImage(res.tempImagePath, isEdg ? 90 : 0, rotateRes => {
            this.tempImagePath = rotateRes.tempFilePath
            const edgImgRes = isEdg ? rotateRes : res
            this.canvasWidth = edgImgRes.width
            this.canvasHeight = edgImgRes.height
            console.log('---------rotateRes',rotateRes)
            this.drawCanvas('#canvasView', 'draw').then(imgPath => {
              hideLoading()
              console.log('---------imgPath',imgPath)
              uni.saveImageToPhotosAlbum({
                filePath: imgPath,
                complete: e => {
                  showToast(e.errMsg.includes('fail cancel') ? '保存失败' : '保存成功')
                  this.tempImagePath = ''
                  // 删除临时文件目录图片
                  deleteWxFile()
                },
              })
            }).catch(e => {
              hideLoading()
              showToast('报错了'+e)
              console.log('---------e',e)
            })
          })
        },
      })
    },
    //  切换摄像头
    setDevice() {
      this.device = this.device === 'back' ? 'front' : 'back'
      const text = this.device === 'back' ? '后置' : '前置'
      showToast(`摄像头${text}`)
    },
    //  闪光灯开关
    setFlash() {
      this.flash = this.flash === 'torch' ? 'off' : 'torch'
    },
    // 选择位置信息
    chooseLocaClick() {
      uni.chooseLocation({
        success: res => {
          locationToAddress(res).then(loca => {
            this.address = `${loca.address_component.city}${loca.formatted_addresses.recommend}`
            // 选择完位置更新画图
            this.drawCanvas('#canvasView', 'init')
          })
        },
      })
    },
    // 时间转换
    formatTime() {
      const date = new Date()
      const [year, month, day, hour, minute] = [date.getFullYear(), String(date.getMonth() + 1).padStart(2, '0'), String(date.getDate()).padStart(2, '0'), String(date.getHours()).padStart(2, '0'), String(date.getMinutes()).padStart(2, '0')]
      const weekDay = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()]
      return {
        date: `${year}-${month}-${day}`,
        time: `${hour}:${minute}`,
        week: `星期${weekDay}`,
      }
    },
  },
}
</script>
<style lang="scss">
.handle {
  position: fixed;
  bottom: 0;
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  font-size: 28rpx;
  background: rgb(255, 255, 255);
}
.handle_ps,
.handle_card {
  display: flex;
  flex-direction: column;
  text-align: center;
  height: 75px;
  line-height: 25px;
  background: #ffffff;
  padding: 0;
  font-size: 25rpx;
  margin: 15rpx 0;
}
.handle_ps,
.handle_card {
  &::after {
    border: none;
  }
}
.handle_ps_image {
  width: 50px;
  height: 50px;
}
.handle_card_name {
  font-size: 25rpx;
}
.handle_card_icon {
  width: 40px;
  height: 40px;
  margin: 5px;
}
</style>
